﻿# 基本设置
$projectDir = ".\blog_manager"
$pythonDir = "$projectDir\.venv"
$djangoVersion = "5.0.12"
$pypiSource = "https://pypi.tuna.tsinghua.edu.cn/simple"
$gitRepo = "https://gitee.com/cooltange/blog_manager_2025.git"
$gitVersion = $args[0]

# 检查Git是否安装
try {
    $null = Get-Command git -ErrorAction Stop
} catch {
    Write-Host "Git未安装！请先安装Git: https://git-scm.com/downloads" -ForegroundColor Red
    Read-Host "按回车键退出"
    exit 1
}

# 删除之前创建的文件夹
Write-Host "删除之前创建的文件夹..." -ForegroundColor Yellow
if (Test-Path $pythonDir) { Remove-Item -Path $pythonDir -Recurse -Force }
if (Test-Path $projectDir) { Remove-Item -Path $projectDir -Recurse -Force }

# 创建项目目录
Write-Host "创建项目目录: $projectDir" -ForegroundColor Green
New-Item -ItemType Directory -Path $projectDir -Force | Out-Null

# 解压 Python 3.11.9 便携版本
Write-Host "解压 Python 3.11.9 便携版本..." -ForegroundColor Green
Expand-Archive -Path ".\software\python-3.11.9-embed-amd64.zip" -DestinationPath "$projectDir\python" -Force

# 配置便携版Python以支持pip和包安装
Write-Host "配置便携版Python..." -ForegroundColor Green
Add-Content -Path "$projectDir\python\python311._pth" -Value "import site"

# 安装pip
Write-Host "安装pip..." -ForegroundColor Green
& "$projectDir\python\python.exe" ".\software\get-pip-25.0.1.py" --no-warn-script-location

# 配置pip默认使用清华源
Write-Host "配置便携Python环境的pip默认使用清华源..." -ForegroundColor Green
New-Item -ItemType Directory -Path "$projectDir\python\pip" -Force | Out-Null
@"
[global]
index-url = $pypiSource
"@ | Out-File -FilePath "$projectDir\python\pip\pip.ini" -Encoding UTF8

# 安装virtualenv
Write-Host "安装virtualenv..." -ForegroundColor Green
& "$projectDir\python\Scripts\pip.exe" install ".\software\virtualenv-20.29.3-py3-none-any.whl"

# 创建虚拟环境
Write-Host "创建虚拟环境..." -ForegroundColor Green
& "$projectDir\python\Scripts\virtualenv.exe" "$pythonDir"

# 安装Django使用清华源
Write-Host "安装Django和mysqlclient..." -ForegroundColor Green
& "$pythonDir\Scripts\pip.exe" install "django==$djangoVersion"
& "$pythonDir\Scripts\pip.exe" install "mysqlclient"

# Git仓库设置
Write-Host "配置Git仓库..." -ForegroundColor Green
$currentPath = Get-Location
Set-Location -Path $projectDir

# 初始化Git仓库并拉取代码
git init
git remote add origin $gitRepo

# 获取用户输入的版本号
if ([string]::IsNullOrEmpty($gitVersion)) {
    $userInput = Read-Host "请输入要使用的版本号（直接回车使用最新版本）"
    if ([string]::IsNullOrEmpty($userInput)) {
        Write-Host "使用最新版本..." -ForegroundColor Green
        git pull origin master
    } else {
        Write-Host "切换到指定版本: $userInput" -ForegroundColor Green
        git fetch origin master
        git checkout master
        git reset --hard $userInput
    }
} else {
    Write-Host "使用命令行参数指定的版本: $gitVersion" -ForegroundColor Green
    git fetch origin master
    git checkout master
    git reset --hard $gitVersion
}

# 切换回原始目录
Set-Location -Path $currentPath

Write-Host "项目设置完成！" -ForegroundColor Cyan
Read-Host "按回车键继续"
